<template>
  <div style="height: 100%;width: 100%;" v-loading="showLoading&&loading">
    <div id="tb_tableTxt_Container" style="height: 100%" v-if="workBook.chartMode===6">
      <table id="tb_tableTxt" style="height: 100%"></table>
    </div>
    <div v-else-if="workBook.chartMode===19" class="msContain msContainSimple"
         style="background: transparent; border: none;">
      <div class="msMain" :style="workBook.chartConfig.style">
        <div class="msMainValue"
             :style="workBook.chartConfig.style.measure">
          {{ currentEditChart.msMainValue }}
        </div>
        <div class="msFooterValue" :title="currentEditChart.msMainTitle"
             :style="workBook.chartConfig.style.title">
          {{ workBook.chartConfig.style.title.content || currentEditChart.msMainTitle }}
          <span
            :style="{...workBook.chartConfig.style.percent,color:currentEditChart.msFooter_1_Flag=='up'?workBook.chartConfig.style.percent.color1:workBook.chartConfig.style.percent.color2}"
            v-show="currentEditChart.msFooter_0_Value">
            <i
              :class="currentEditChart.msFooter_1_Flag=='up'?'glyphicon glyphicon-arrow-up':'glyphicon glyphicon-arrow-down'"
              :style="workBook.chartConfig.style.icon"></i>
            {{ currentEditChart.msFooter_1_Value }}
          </span>
        </div>
      </div>
    </div>
    <div id="chart" style="height: 100%;width: 100%;" v-else></div>
  </div>
</template>

<script>
import {onMounted, onUnmounted, ref, toRefs, watch, reactive} from 'vue';
import {Chart} from '@/components/chart';
import {store as shared} from "@/components/chart/common/store";
import {addListener} from "resize-detector";
import {getWorkBook, loadData, parseToObj} from "@/api/workBook";
import {getDataSource} from "@/api/dataSource";
import {changeTone, getChartConfigByChartMode} from "@/components/chart/common/config";
import {ElMessage} from "element-plus";

export default {
  name: "workBookView",
  props: {
    workBookId: String
  },
  data() {
    return {
      loading: false, //加载状态
      showLoading: true, //是否显示loading
      data: [],  //缓存数据
      shared: shared
    }
  },
  setup(props) {
    const {workBookId} = toRefs(props);
    const state = reactive({
      workBook: {},
      dataSource: {},
      timer: {},
      currentEditChart:{}
    })
    const loadWorkBook = async () => {
      let workBookResp = await getWorkBook(workBookId.value);
      if (workBookResp.data) {
        state.dataSource = await getDataSource(workBookResp.data.dataSourceId);
        state.workBook = parseToObj(workBookResp.data);
      } else {
        ElMessage.error("没有找到对应的图表，请检查参数是否正确：" + workBookId.value)
      }
    }
    onMounted(() => {
      if (workBookId.value) {
        loadWorkBook();
      } else {
        state.workBook = state.dataSource = {}
      }
    })
    watch(workBookId, () => {
      if (workBookId.value) {
        loadWorkBook();
      } else {
        state.workBook = state.dataSource = {}
      }
    })
    onUnmounted(() => {
      if (state.timer) {
        clearInterval(state.timer)
      }
      removeChart();
    })
    //销毁图表实例
    const removeChart = () => {
      if (state.currentEditChart && state.currentEditChart.removeChart) {
        state.currentEditChart.removeChart();
      }
    }
    return {
      ...toRefs(state),
      removeChart
    }
  },
  methods: {
    //刷新图表
    refreshChart(workBook, data, dataSource) {
      this.loading = false
      if (!data && this.data.length === 0) {
        return false;
      }
      //缓存data
      if (!data) {
        data = this.data
      } else {
        this.data = data
      }
      this.workBook = workBook;
      if (dataSource) {
        this.dataSource = dataSource;
      }
      //获取默认图表配置
      if (!this.workBook.chartConfig) {
        this.workBook.chartConfig = getChartConfigByChartMode(this.workBook.chartMode);
      }

      if (typeof this.workBook.chartConfig === "string") {
        this.workBook.chartConfig = JSON.parse(this.workBook.chartConfig);
      }

      let _currentChartMode = workBook.chartMode

      //处于自动更新数据的状态
      if (this.timer && workBook.autoUpdate > 0 && this.currentEditChart) {
        this.loading = false;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.loadData()
        }, workBook.autoUpdate * 60 * 1000);
        if (this.currentEditChart.update) {
          this.currentEditChart.update(data);
          return false;
        }
      }

      this.removeChart();

      const columnFields = workBook.columns;
      const rowFields = workBook.rows;

      //构建图表
      this.$nextTick(() => {
        this.currentEditChart = Chart.build(this.$el, data, columnFields, rowFields, _currentChartMode, {
          colorMark: workBook.colorMark,
          scale: 1,
          isYoy: workBook.isYoy,
          rankMark: {},
          gauge: {},
          chartConfig: workBook.chartConfig,
          autoUpdate: workBook.autoUpdate,
          dataMarking: workBook.dataMarking
        });
      })

      if (!this.currentEditChart) {
        return false;
      }

      //自动刷新
      if (workBook.autoUpdate > 0 && !this.timer) {
        this.showLoading = false;
        this.timer = setTimeout(() => {
          this.loadData()
        }, workBook.autoUpdate * 1000);
      }
    },
    //分析界面请求数据
    loadData(dashboard) {
      this.loading = true
      if (this.workBook.id && this.dataSource.id) {
        loadData(this.workBook, this.dataSource, dashboard).then(data => {
          this.data = data
          //刷新图表
          this.refreshChart(this.workBook, data)
        })
      }
    },

  },
  mounted() {
    const _this = this
    addListener(_this.$el, () => {
      if (_this.currentEditChart && _this.currentEditChart.resize) {
        _this.currentEditChart.resize();
      }
    })
    if (this.workBook.rows || this.workBook.columns) {
      this.loadData();
    }
  },
  watch: {
    'shared.darkMode'() {
      if (this.workBook.chartMode) {
        changeTone(this.workBook)
        this.refreshChart(this.workBook, this.data);
      }
    },
    'shared.enableDecal'() {
      this.refreshChart(this.workBook, this.data);
    },
    'shared.runHash'() {
      if (shared.globalFilter) {
        //全局筛选
        this.workBook.globalFilter = shared.globalFilter
      }
      this.loadData(shared.dashboard);
    },
    workBook() {
      if (this.workBookId && this.workBook.id && this.dataSource.id) {
        this.loadData();
      }
    }
  }
}
</script>

<style scoped>
</style>
